package com.viboo.concern.controller;

import com.google.gson.Gson;
import com.viboo.concern.entity.ChatInfo;
import com.viboo.concern.entity.ChatMessage;
import com.viboo.concern.entity.ChatSignature;
import com.viboo.concern.entity.ChatToken;
import com.viboo.concern.response.ResultUtil;
import com.viboo.concern.service.impl.ChatInfoServiceImpl;
import com.viboo.concern.util.BaseException;
import com.viboo.concern.util.TextUtils;
import com.viboo.concern.util.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author avanline
 * @descriotion
 * @date 2018-03-08 13:50
 */
@RestController
@RequestMapping("follow")
@Slf4j
public class FollowController {

    @Autowired
    ChatInfoServiceImpl chatInfoService;

    @PostMapping(value = "send")
    String sendMessage(@RequestBody String ToUserName, ChatSignature chatSignature,
                       HttpServletRequest request) {
        log.info(chatSignature.toString());
        log.info(ToUserName);
        ChatMessage chatMessage = new Gson().fromJson(ToUserName, ChatMessage.class);
        if (chatMessage != null && !TextUtils.isEmpty(chatMessage.getFromUserName()))
            sendChatMessage(chatMessage.getFromUserName(), request);
        return chatSignature.getEchostr();
    }

    private void sendChatMessage(String openId, HttpServletRequest request) {
        try {
            ChatInfo mChatInfo = chatInfoService.select();
            if (mChatInfo == null) {
                log.info("没有推送消息");
                return;
            }
            String access_token = WeChatUtil.getToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token;
            Map<String, Object> map = new HashMap<>();
//            map.put("access_token", mChatToken.access_token);
            map.put("touser", openId);
            map.put("msgtype", "link");
            Map<String, String> linkMap = new HashMap<>();
            if (TextUtils.isEmpty(mChatInfo.getChatTitle()))
                linkMap.put("title", "点击进入，查看谁是最关心你的人");
            else
                linkMap.put("title", mChatInfo.getChatTitle());
            if (TextUtils.isEmpty(mChatInfo.getChatContent()))
                linkMap.put("description", "朋友关心度指数");
            else
                linkMap.put("description", mChatInfo.getChatContent());

            linkMap.put("url", mChatInfo.getChatUrl());
            if (TextUtils.isEmpty(mChatInfo.getThumbUrl())) {
                String path = "http://" + request.getServerName() + request.getContextPath();//项目图片路径
                String sharePath = path + ("/images/ic_chat_thumb.jpg");
                linkMap.put("thumb_url", sharePath);
            } else
                linkMap.put("thumb_url", mChatInfo.getThumbUrl());
            map.put("link", linkMap);
            RestTemplate rest = new RestTemplate();
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(map, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);

            byte[] result = entity.getBody();
            log.info("返回数据长度:{}", result.length);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(result);
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder mStringBuilder = new StringBuilder();
            while ((line = in.readLine()) != null) {
                mStringBuilder.append(line);
            }
            log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + mStringBuilder.toString());
        } catch (BaseException | IOException e) {
            e.printStackTrace();
        }
    }

}
